package com.d3works.apps.account.service.move;

import com.d3works.apps.account.db.Move;
import com.d3works.apps.account.db.MoveLine;
import com.d3works.apps.account.db.repo.MoveRepository;
import com.d3works.apps.account.exception.AccountExceptionMessage;
import com.d3works.apps.account.service.config.AccountConfigService;
import com.d3works.apps.base.db.repo.PeriodRepository;
import com.d3works.exception.D3worksException;
import com.d3works.exception.db.repo.TraceBackRepository;
import com.d3works.i18n.I18n;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
import java.math.BigDecimal;

public class MoveCancelService {

  protected MoveRepository moveRepository;
  protected AccountConfigService accountConfigService;

  @Inject
  public MoveCancelService(
      AccountConfigService accountConfigService, MoveRepository moveRepository) {

    this.accountConfigService = accountConfigService;
    this.moveRepository = moveRepository;
  }

  @Transactional(rollbackOn = {Exception.class})
  public void cancel(Move move) throws D3worksException {

    if (move == null) {
      return;
    }

    for (MoveLine moveLine : move.getMoveLineList()) {

      if (moveLine.getAccount().getUseForPartnerBalance()
          && moveLine.getAmountPaid().compareTo(BigDecimal.ZERO) != 0) {
        throw new D3worksException(
            move,
            TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
            I18n.get(AccountExceptionMessage.MOVE_CANCEL_1));
      }
    }

    if (move.getPeriod() == null
        || move.getPeriod().getStatusSelect() == PeriodRepository.STATUS_CLOSED) {
      throw new D3worksException(
          move,
          TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
          I18n.get(AccountExceptionMessage.MOVE_CANCEL_2));
    }

    if (move.getStatusSelect().equals(MoveRepository.STATUS_ACCOUNTED)) {
      throw new D3worksException(
          move,
          TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
          I18n.get(AccountExceptionMessage.MOVE_CANCEL_4));
    }

    try {

      if (move.getStatusSelect() == MoveRepository.STATUS_NEW) {
        moveRepository.remove(move);
      } else {
        move.setStatusSelect(MoveRepository.STATUS_CANCELED);
        moveRepository.save(move);
      }

    } catch (Exception e) {

      throw new D3worksException(
          move,
          TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
          I18n.get(AccountExceptionMessage.MOVE_CANCEL_3));
    }
  }
}
